package cn.enn.smart.conf;

import cn.enn.smart.filter.MobileLoginFilter;
import cn.enn.smart.filter.ValidateCodeFilter;
import cn.enn.smart.properties.EnnSecurityValidateCodeProperties;
import cn.enn.smart.service.ValidateCodeService;
import cn.enn.smart.service.impl.DefaultValidateCodeServiceImpl;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

@Configuration
public class EnnValidateCodeSecurityConfigurer extends EnnSecurityConfigurer {

	@Autowired
	private EnnSecurityValidateCodeProperties properties;

	@Autowired
	private AuthenticationFailureHandler failureHandler;

	@Autowired
	private ValidateCodeService validateCodeService;

	@Override
	public void configure(HttpSecurity http) throws Exception {
		Set<String> processUrls = properties.getProcessUrls();
		ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter(processUrls, failureHandler);
		validateCodeFilter.setPostOnly(properties.isPostOnly());
		validateCodeFilter.setValidateCodeParameter(properties.getParameter());
		validateCodeFilter.setValidateCodeUniqueKey(properties.getUniqueKey());
		validateCodeFilter.setValidateCodeService(validateCodeService);
		http.addFilterBefore(validateCodeFilter, MobileLoginFilter.class);
	}

	@Configuration
	public static class AutoValidateCodeConfiguration {

		@Bean
		@ConditionalOnMissingBean(ValidateCodeService.class)
		public ValidateCodeService validateCodeService() {
			return new DefaultValidateCodeServiceImpl();
		}
	}
}
